<template>
  <div class="my-posts-container">
    <div class="banner">
      <div class="banner-content">
        <h1>我的帖子</h1>
        <p>管理您在论坛发布的帖子</p>
      </div>
    </div>
    
    <div class="content-section">
      <div class="filter-bar">
        <div class="total-count">
          共发布了 <span class="count-num">{{ total }}</span> 篇帖子
        </div>
        <div class="search-filters">
          <el-input 
            v-model="searchTitle" 
            placeholder="搜索标题" 
            prefix-icon="el-icon-search" 
            clearable 
            @clear="handleSearch" 
            @keyup.enter.native="handleSearch"
            size="small"
            class="search-input">
          </el-input>
          <el-select 
            v-model="selectedTopic" 
            placeholder="选择类别" 
            clearable 
            @change="handleSearch"
            size="small"
            class="topic-select">
            <el-option 
              v-for="topic in topicsList"
              :key="topic.topicId"
              :label="topic.topicName"
              :value="topic.topicId">
            </el-option>
          </el-select>
        </div>
        <div class="sort-options">
          <span class="sort-label">排序方式：</span>
          <el-radio-group v-model="sortType" size="small" @change="handleSortChange">
            <el-radio-button label="newest">最新时间</el-radio-button>
            <el-radio-button label="most_views">最多浏览</el-radio-button>
            <el-radio-button label="most_comments">最多评论</el-radio-button>
            <el-radio-button label="most_likes">最多点赞</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      
      <div v-loading="loading" class="posts-list">
        <template v-if="postsList.length > 0">
          <div 
            v-for="post in postsList" 
            :key="post.postId" 
            class="post-card">
            <div class="post-header">
              <h3 class="post-title" @click="viewPostDetail(post.postId)">{{ post.title }}</h3>
              <div class="post-tag" v-if="post.topicId">{{ getTopicName(post.topicId) }}</div>
            </div>
            <div class="post-content">
              <p class="post-summary">{{ post.content | truncate }}</p>
            </div>
            <div class="post-footer">
              <div class="post-meta">
                <span class="post-time">发布于 {{ formatTime(post.createTime) }}</span>
                <div class="post-stats">
                  <span><i class="el-icon-view"></i> {{ post.views || 0 }}</span>
                  <span><i class="el-icon-chat-dot-round"></i> {{ post.comments || 0 }}</span>
                  <span><i class="fa-solid fa-heart"></i> {{ post.likes || 0 }}</span>
                </div>
              </div>
              <div class="post-actions">
                <el-button type="primary" size="small" icon="el-icon-view" @click="viewPostDetail(post.postId)">查看</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="confirmDeletePost(post)">删除</el-button>
              </div>
            </div>
          </div>
        </template>
        
        <div v-if="postsList.length === 0 && !loading" class="empty-state">
          <i class="el-icon-document"></i>
          <p>您还没有发布任何帖子</p>
          <el-button type="primary" @click="goToForum">去论坛发帖</el-button>
        </div>
      </div>

      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <div class="delete-dialog-content">
        <i class="el-icon-warning warning-icon"></i>
        <p>确定要删除帖子 <strong>{{ currentPost ? currentPost.title : '' }}</strong> 吗？</p>
        <p class="delete-notice">删除后将无法恢复，相关评论也将被删除。</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="deletePost" :loading="deleteLoading">确定删除</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request'

export default {
  name: 'MyPostsVue',
  filters: {
    truncate(value) {
      if (!value) return '';
      if (value.length <= 100) return value;
      return value.substring(0, 100) + '...';
    }
  },
  data() {
    return {
      loading: false,
      postsList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      sortType: 'newest', // 排序方式：time - 发布时间，views - 浏览次数，comments - 评论数量
      topicsList: [],
      deleteDialogVisible: false,
      currentPost: null,
      deleteLoading: false,
      searchTitle: '',
      selectedTopic: null
    };
  },
  created() {
    document.title = '京剧苑 - 我的帖子';
    window.scrollTo(0, 0);
    this.checkLogin();
    this.initData();
  },
  methods: {
    // 检查用户是否登录
    checkLogin() {
      const token = localStorage.getItem('token');
      if (!token) {
        this.$message.error('您尚未登录，请先登录');
        this.$router.push('/login');
      }
    },
    
    // 初始化数据
    initData() {
      this.fetchTopics();
      this.fetchMyPosts();
    },
    
    // 获取所有专题
    fetchTopics() {
      service.get('/api/forum/topic/getTopicLists').then(res => {
        if (res.code === 200) {
          this.topicsList = res.data;
        }
      }).catch(err => {
        this.$message.error('获取专题列表失败');
        console.error('获取专题列表失败:', err);
      });
    },
    
    // 获取我的帖子
    fetchMyPosts() {
      this.loading = true;
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        title: this.searchTitle,
        topicId: this.selectedTopic,
        token: localStorage.getItem('token'),
        sortBy: this.sortType
      };
      
      if (this.searchTitle) {
        params.title = this.searchTitle;
      }
      
      if (this.selectedTopic) {
        params.topicId = this.selectedTopic;
      }
      
      service.get('/api/forum/post/myPosts', { params }).then(res => {
        if (res.code === 200) {
          console.log(res.data);
          this.postsList = res.data.list || [];
          this.total = res.data.total || 0;
        } else {
          this.$message.error(res.msg || '获取帖子列表失败');
        }
      }).catch(err => {
        this.$message.error('获取帖子列表失败');
        console.error('获取帖子列表失败:', err);
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },
    
    // 获取专题名称
    getTopicName(topicId) {
      const topic = this.topicsList.find(t => t.topicId === topicId);
      return topic ? topic.topicName : '未分类';
    },
    
    // 排序方式改变
    handleSortChange() {
      this.currentPage = 1;
      this.fetchMyPosts();
    },
    
    // 分页大小改变
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchMyPosts();
    },
    
    // 当前页改变
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchMyPosts();
    },
    
    // 查看帖子详情
    viewPostDetail(postId) {
      this.$router.push(`/forum/post/${postId}`);
    },
    
    // 确认删除帖子
    confirmDeletePost(post) {
      this.currentPost = post;
      this.deleteDialogVisible = true;
    },
    
    // 删除帖子
    deletePost() {
      if (!this.currentPost) return;
      
      this.deleteLoading = true;
      service.delete(`/api/forum/post/deletePost/${this.currentPost.postId}`).then(res => {
        if (res.code === 200) {
          this.$message.success('删除帖子成功');
          this.deleteDialogVisible = false;
          this.fetchMyPosts(); // 重新加载帖子列表
        } else {
          this.$message.error(res.msg || '删除帖子失败');
        }
      }).catch(err => {
        this.$message.error('删除帖子失败');
        console.error('删除帖子失败:', err);
      }).finally(() => {
        this.deleteLoading = false;
      });
    },
    
    // 前往论坛页面
    goToForum() {
      this.$router.push('/forum');
    },
    
    // 处理搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchMyPosts();
    }
  }
}
</script>

<style scoped>
.my-posts-container {
  min-height: 100vh;
  padding-bottom: 50px;
  background-color: #f9f5f0;
}

.banner {
  height: 500px;
  background-image: url('../assets/opera_5.jpg');
  background-size: cover;
  background-position: center;
  position: relative;
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.banner:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(139, 0, 0, 0.7), rgba(0, 0, 0, 0.5));
}

.banner-content {
  position: relative;
  z-index: 1;
  text-align: center;
  color: white;
}

.banner-content h1 {
  font-size: 4rem;
  font-family: 'STXingkai', 'STZhongsong', serif;
  margin-bottom: 15px;
  text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.6);
  color: #FFD700;
  letter-spacing: 10px;
}

.banner-content p {
  font-size: 1.4rem;
  max-width: 600px;
  margin: 0 auto;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.6);
  letter-spacing: 3px;
}

.content-section {
  padding: 30px 8%;
  max-width: 1200px;
  margin: 0 auto;
  background-color: transparent;
  box-shadow: none;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border-bottom: none;
}

.total-count {
  font-size: 1.1rem;
  color: #666;
}

.count-num {
  font-weight: bold;
  color: #8B0000;
  font-size: 1.3rem;
  margin: 0 3px;
}

.search-filters {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.topic-select {
  width: 150px;
}

.sort-options {
  display: flex;
  align-items: center;
}

.sort-label {
  font-size: 1rem;
  color: #666;
  margin-right: 10px;
}

.posts-list {
  min-height: 300px;
}

.post-card {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: none;
  padding: 20px;
  margin-bottom: 30px;
}

.post-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(139, 0, 0, 0.15);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.post-title {
  font-size: 1.4rem;
  color: #333;
  margin: 0;
  cursor: pointer;
  transition: color 0.3s ease;
  flex: 1;
  font-weight: 600;
}

.post-title:hover {
  color: #8B0000;
}

.post-tag {
  background-color: #f0f0f0;
  color: #666;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  margin-left: 10px;
}

.post-content {
  margin-bottom: 20px;
}

.post-summary {
  color: #666;
  line-height: 1.6;
  margin: 0;
  font-size: 0.95rem;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.post-time {
  color: #999;
  font-size: 0.9rem;
  margin-bottom: 8px;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 15px;
}

.post-stats .el-icon-view {
  color: #409EFF;
}

.post-stats .el-icon-chat-dot-round {
  color: #67C23A;
}

.post-stats .fa-solid {
  color: #ff4757;
}

.post-stats span {
  color: #666;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
}

.post-stats i {
  margin-right: 5px;
  font-size: 1rem;
}

.post-actions {
  display: flex;
  gap: 10px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #999;
  background: #fff;
  border-radius: 8px;
  margin: 20px 0;
}

.empty-state i {
  font-size: 4rem;
  margin-bottom: 20px;
  color: #ddd;
}

.empty-state p {
  font-size: 1.3rem;
  margin-bottom: 25px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 10px 0;
}

/* 删除确认对话框 */
.delete-dialog-content {
  text-align: center;
  padding: 20px 0;
}

.warning-icon {
  font-size: 3rem;
  color: #E6A23C;
  margin-bottom: 15px;
}

.delete-notice {
  color: #F56C6C;
  font-size: 0.9rem;
  margin-top: 10px;
}

@media (max-width: 768px) {
  .banner {
    height: 350px;
  }
  
  .banner-content h1 {
    font-size: 2.8rem;
    letter-spacing: 6px;
  }
  
  .banner-content p {
    font-size: 1.1rem;
    letter-spacing: 2px;
  }
  
  .content-section {
    padding: 20px 5%;
  }
  
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-filters {
    width: 100%;
  }
  
  .search-input, .topic-select {
    width: 100%;
  }
  
  .post-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .post-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 480px) {
  .banner {
    height: 250px;
  }
  
  .banner-content h1 {
    font-size: 2rem;
    letter-spacing: 4px;
  }
  
  .banner-content p {
    font-size: 1rem;
    letter-spacing: 1px;
  }
  
  .content-section {
    padding: 15px 3%;
  }
  
  .post-header {
    flex-direction: column;
  }
  
  .post-tag {
    margin-left: 0;
    margin-top: 5px;
    align-self: flex-start;
  }
  
  .post-title {
    font-size: 1.2rem;
  }
}
</style> 